﻿using AutoMapper;
using GuanYijia.Application.IntPut;
using GuanYijia.Application.OutPut;
using GuanYijia.DoMain;
using GuanYijia.DoMain.PageDto;
using GuanYijia.DoMain.RBAC;
using GuanYijia.EntityFarmeworkCore;
using GuanYijia.Repository;
using Microsoft.AspNetCore.Mvc;
using MySqlConnector;
using Panda.DynamicWebApi;
using Panda.DynamicWebApi.Attributes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace GuanYijia.Application.WarehouseManagement
{
    [DynamicWebApi]
    [ApiExplorerSettings(GroupName = "v1")]
    public class WarehouseAddDataService : IDynamicWebApi
    {
        private readonly IBaseRepository<ProductInfo> _productInfoRepository;
        private readonly IBaseRepository<Product_Current_Stock> _currentstockRepository;
        private readonly IBaseRepository<Product_Price> _priceRepository;
        private readonly IBaseRepository<MaterialCategory> _categoryRepository;
        private readonly IBaseRepository<Warehouse> _warehouseRepository;
        private readonly IBaseRepository<Other_Warehousing_Head> _headRepository;
        private readonly IBaseRepository<Other_Warehousing_Item> _itemRepository;
        private readonly IBaseRepository<Supplier> _supplierRepository;
        private readonly IBaseRepository<User> _userRepository;
        public WarehouseAddDataService(IBaseRepository<ProductInfo> productInfoRepository, IBaseRepository<Product_Current_Stock> currentstockRepository, IBaseRepository<Product_Price> priceRepository, IBaseRepository<MaterialCategory> categoryRepository, IBaseRepository<Warehouse> warehouseRepository, IBaseRepository<Other_Warehousing_Head> headRepository, IBaseRepository<Other_Warehousing_Item> itemRepository, IBaseRepository<Supplier> supplierRepository, IBaseRepository<User> userRepository)
        {
            _productInfoRepository = productInfoRepository;
            _currentstockRepository = currentstockRepository;
            _priceRepository = priceRepository;
            _categoryRepository = categoryRepository;
            _warehouseRepository = warehouseRepository;
            _headRepository = headRepository;
            _itemRepository = itemRepository;
            _supplierRepository = supplierRepository;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 其他入库显示
        /// </summary>
        /// <param name="request">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public PageResultDto<OtherAddShowOutPut> GetOtherAddShow(GetOtherAddIntPut request)
        {
            var res = new PageResultDto<OtherAddShowOutPut>() { TotalCount = 0, TotalPage = 0, Data = new List<OtherAddShowOutPut>() };
            var list = from a in _headRepository.GetQueryable(tracking: false)
                       join b in _supplierRepository.GetQueryable(tracking: false) on a.organ_id equals b.SupplierId
                       join c in _userRepository.GetQueryable(tracking: false) on a.creator_id equals c.userId
                       where a.type == "入库" && !a.delete_flag
                       select new OtherAddShowOutPut
                       {
                           otherHeadId = a.otherheadId,
                           organ_name = b.supplier,
                           organ_id = b.SupplierId,
                           number = a.number,
                           link_number = a.link_number,
                           product_info = a.product_info,
                           create_time = a.create_time,
                           userId = c.userId,
                           username = c.username,
                           total_num = a.total_num,
                           total_price = a.total_price,
                           remark = a.remark,
                           statusstr = a.status == true ? "已审核" : "未审核",
                           status = a.status
                       };
            if (!string.IsNullOrEmpty(request.number))
            {
                list = list.Where(p => p.number.Contains(request.number));
            }
            if (!string.IsNullOrEmpty(request.keywords))
            {
                list = list.Where(p => p.product_info.Contains(request.keywords));
            }
            if (request.start_time != null)
            {
                list = list.Where(p => p.create_time <= request.start_time && p.create_time >= request.end_time);
            }
            if (request.organ_id != null)
            {
                list = list.Where(p => p.organ_id == request.organ_id);
            }
            if (request.depot_id != null)
            {
                var itemNolist = _itemRepository.GetQueryable(tracking: false).Where(p => p.depot_id == request.depot_id);
                var list2 = itemNolist.Select(p => p.header_id).ToList();
                list = list.Where(p => list2.Contains(p.otherHeadId));
            }
            res.TotalCount = list.Count();
            res.TotalPage = (int)Math.Ceiling(res.TotalCount * 1.0 / request.pagesize);
            res.Data = list.OrderByDescending(p => p.otherHeadId).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize).ToList();
            return res;
        }

        public async Task<ResponseModelDto> InsertOtherAdd(AddOtherAddHeadIntPut info)
        {
            var res = new ResponseModelDto();

            // 创建事务
            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var time = DateTime.Now;

                    #region 订单表添加数据
                    Other_Warehousing_Head head = new Other_Warehousing_Head();
                    var first = 1;
                    foreach (var item in info.items)
                    {
                        if (first == 1)
                        {
                            head.product_info += item.product_name + "(" + item.standard + item.model + item.color + ")";
                        }
                        else
                        {
                            head.product_info += "," + item.product_name + item.standard + item.model + item.color;
                        }
                        first++;
                    }
                    head.type = info.type;
                    head.default_number = info.number;
                    head.number = info.number;
                    head.create_time = time;
                    head.organ_id = info.organ_id;
                    head.hands_person_id = info.hands_person_id;
                    head.creator_id = info.creator_id;
                    head.total_price = info.total_price;
                    head.total_num = info.total_num;
                    head.remark = info.remark;
                    head.file_name = info.file_name;
                    head.status = info.status;
                    head.link_number = info.link_number;
                    head.tenant_id = 1;
                    await _headRepository.InsertAsync(head);
                    #endregion

                    #region 订单详情表添加数据
                    List<Other_Warehousing_Item> itemlist = new List<Other_Warehousing_Item>();
                    foreach (var item in info.items)
                    {
                        Other_Warehousing_Item items = new Other_Warehousing_Item();
                        items.header_id = head.otherheadId;
                        items.product_id = item.product_id;
                        items.bar_code = item.bar_code;
                        items.product_name = item.product_name;
                        items.standard = item.standard;
                        items.color = item.color;
                        items.product_unit = item.product_unit;
                        items.oper_number = item.oper_number;
                        items.unit_price = item.unit_price;
                        items.all_price = item.all_price;
                        items.remark = item.remark;
                        items.another_depot_id = item.another_depot_id;
                        items.tenant_id = 1;
                        itemlist.Add(items);
                    }
                    await _itemRepository.InsertRangeAsync(itemlist);
                    #endregion

                    #region 商品当前库存修改数量
                    var productIds = info.items.Select(p => p.product_id);
                    var currt = _currentstockRepository.GetQueryable().Where(p => productIds.Contains(p.product_id)).ToList();
                    currt.ForEach(p =>
                    {
                        var itemsModel = info.items.FirstOrDefault(a => a.product_id == p.product_id);
                        if (itemsModel == null) // 如果为null则表示有系统内部错误
                        {
                            throw new Exception("系统错误，找不到编码" + p.currentid + "的商品");
                        }
                        p.current_number += itemsModel.oper_number;
                    });
                    await _currentstockRepository.UpdateRangeAsync(currt);
                    #endregion

                    // 提交事务
                    transaction.Complete();

                    res.Code = 1;
                    res.Message = "操作成功";
                }
                catch (Exception ex)
                {
                    // 捕获异常，返回失败消息
                    res.Code = 0;
                    res.Message = $"操作失败: {ex.Message}";
                }
            }
            return res;
        }

        /// <summary>
        /// 其他出库显示
        /// </summary>
        /// <param name="request">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public PageResultDto<OtherAddShowOutPut> GetOtherOutShow(GetOtherAddIntPut request)
        {
            var res = new PageResultDto<OtherAddShowOutPut>() { TotalCount = 0, TotalPage = 0, Data = new List<OtherAddShowOutPut>() };
            var list = from a in _headRepository.GetQueryable(tracking: false)
                       join b in _supplierRepository.GetQueryable(tracking: false) on a.organ_id equals b.SupplierId
                       join c in _userRepository.GetQueryable(tracking: false) on a.creator_id equals c.userId
                       where a.type == "出库" && !a.delete_flag
                       select new OtherAddShowOutPut
                       {
                           otherHeadId = a.otherheadId,
                           organ_name = b.supplier,
                           organ_id = b.SupplierId,
                           number = a.number,
                           link_number = a.link_number,
                           product_info = a.product_info,
                           create_time = a.create_time,
                           userId = c.userId,
                           username = c.username,
                           total_num = a.total_num,
                           total_price = a.total_price,
                           remark = a.remark,
                           statusstr = a.status == true ? "已审核" : "未审核",
                           status = a.status
                       };
            if (!string.IsNullOrEmpty(request.number))
            {
                list = list.Where(p => p.number.Contains(request.number));
            }
            if (!string.IsNullOrEmpty(request.keywords))
            {
                list = list.Where(p => p.product_info.Contains(request.keywords));
            }
            if (request.start_time != null)
            {
                list = list.Where(p => p.create_time <= request.start_time && p.create_time >= request.end_time);
            }
            if (request.organ_id != null)
            {
                list = list.Where(p => p.organ_id == request.organ_id);
            }
            if (request.depot_id != null)
            {
                var itemNolist = _itemRepository.GetQueryable(tracking: false).Where(p => p.depot_id == request.depot_id);
                var list2 = itemNolist.Select(p => p.header_id).ToList();
                list = list.Where(p => list2.Contains(p.otherHeadId));
            }
            res.TotalCount = list.Count();
            res.TotalPage = (int)Math.Ceiling(res.TotalCount * 1.0 / request.pagesize);
            res.Data = list.OrderByDescending(p => p.otherHeadId).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize).ToList();
            return res;
        }

        public async Task<ResponseModelDto> InsertOtherOut(AddOtherAddHeadIntPut info)
        {
            var res = new ResponseModelDto();

            // 创建事务
            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var time = DateTime.Now;

                    #region 订单表添加数据
                    Other_Warehousing_Head head = new Other_Warehousing_Head();
                    var first = 1;
                    foreach (var item in info.items)
                    {
                        if (first == 1)
                        {
                            head.product_info += item.product_name + "(" + item.standard + item.model + item.color + ")";
                        }
                        else
                        {
                            head.product_info += "," + item.product_name + item.standard + item.model + item.color;
                        }
                        first++;
                    }
                    head.type = info.type;
                    head.default_number = info.number;
                    head.number = info.number;
                    head.create_time = time;
                    head.organ_id = info.organ_id;
                    head.hands_person_id = info.hands_person_id;
                    head.creator_id = info.creator_id;
                    head.total_price = info.total_price;
                    head.total_num = info.total_num;
                    head.remark = info.remark;
                    head.file_name = info.file_name;
                    head.status = info.status;
                    head.link_number = info.link_number;
                    head.tenant_id = 1;
                    await _headRepository.InsertAsync(head);
                    #endregion

                    #region 订单详情表添加数据
                    List<Other_Warehousing_Item> itemlist = new List<Other_Warehousing_Item>();
                    foreach (var item in info.items)
                    {
                        Other_Warehousing_Item items = new Other_Warehousing_Item();
                        items.header_id = head.otherheadId;
                        items.product_id = item.product_id;
                        items.bar_code = item.bar_code;
                        items.product_name = item.product_name;
                        items.standard = item.standard;
                        items.color = item.color;
                        items.product_unit = item.product_unit;
                        items.oper_number = item.oper_number;
                        items.unit_price = item.unit_price;
                        items.all_price = item.all_price;
                        items.remark = item.remark;
                        items.another_depot_id = item.another_depot_id;
                        items.tenant_id = 1;
                        itemlist.Add(items);
                    }
                    await _itemRepository.InsertRangeAsync(itemlist);
                    #endregion

                    #region 商品当前库存修改数量
                    var productIds = info.items.Select(p => p.product_id);
                    var currt = _currentstockRepository.GetQueryable().Where(p => productIds.Contains(p.product_id)).ToList();
                    currt.ForEach(p =>
                    {
                        var itemsModel = info.items.FirstOrDefault(a => a.product_id == p.product_id);
                        if (itemsModel == null) // 如果为null则表示有系统内部错误
                        {
                            throw new Exception("系统错误，找不到编码" + p.currentid + "的商品");
                        }
                        p.current_number -= itemsModel.oper_number;
                        if (p.current_number < 0) // 如果为null则表示有系统内部错误
                        {
                            throw new Exception("出现超卖现象");
                        }
                    });
                    await _currentstockRepository.UpdateRangeAsync(currt);
                    #endregion

                    // 提交事务
                    transaction.Complete();

                    res.Code = 1;
                    res.Message = "操作成功";
                }
                catch (Exception ex)
                {
                    // 捕获异常，返回失败消息
                    res.Code = 0;
                    res.Message = $"操作失败: {ex.Message}";
                }
            }
            return res;
        }
    }
}
